const {Student,Op}  = require('../sequelize/sequelize')

  fn_index= async (ctx)=>{

    await Student.findAll().then(res=>{
        ctx.body=res
    })

}

fn_data= async (ctx)=>{

    let keyword = ctx.request.query.keyword

    console.log(isNaN(keyword));


    if(keyword!==''){

        if (isNaN(keyword)==false) {
            let data = await Student.findAll({
                where:{
                        [Op.or]:[
                            {id:keyword},
                            {abstract:keyword},
                            {content:keyword},
                            {classify:keyword},
                            {author:keyword},
                            {dataa:kr=keyword}
                        ]
                }
            })
            ctx.body=data
        }else{
            let data = await Student.findAll({
                where:{
                        [Op.or]:[
                            {name:keyword},
                            {abstract:keyword}
                        ]
                }
            })
            ctx.body=data
        }
    }else{

        await Student.findAll().then(res=>{
        ctx.body=res
        })
    }
    
}

fn_add= async (ctx)=>{

    let data = await Student.findAll().then(res=>{

        let max = 0
        for (let i in res) {
              
        if (max<res[i].id) {
                max=res[i].id
            }
        }
    
        let data = ctx.request.body
    
        data.id=max+1
    
        return data
    })

    await Student.create(data)

    await Student.findAll().then(res=>{
        ctx.body=res
    })
}



fn_edit=async (ctx)=>{
    
    let data= ctx.request.body
    
    await Student.findByPk(data.id).then(async (post)=> {
        await post.update(
            {id:data.id,
            name:data.name,
            abstract:data.abstract,
            content:data.content,
            classify:data.classify,
            author:data.author,
            dataa:data.dataa
        }
        )
    })


    await Student.findAll().then(res=>{
        ctx.body=res
    })
}

fn_Deleted=async (ctx)=>{
    
    let id = ctx.request.query.id

    await Student.destroy({
        where:{id:id}
    })

    await Student.findAll().then(res=>{
        ctx.body=res
    })

}

let get = [['/index',fn_index],['/data',fn_data],['/indexDeleted',fn_Deleted]]
let post =[['/indexadd',fn_add],['/indexedit',fn_edit]]

module.exports={
    'GET':get,
    'POST':post
}